var treeTableShow;
var key = null;
var parentKey = null;
var name= null;
var remark=null;
/**
 * 页面初始化
 */
$(function () {
    //按钮控制
	setPageElementStatus("goodsCategory");


    //后台交互
    $.ajax({
        type:"POST",
        url:"/goodsCategory/isadd.action",
        contentType: "application/json;charset=utf-8",
        dataType: "json",
//        async: false, // 同步
        success:function(data) {
            if (data.success == "y") {
                // if (data.isadd == "y"){
                //     $("#downLoadGoodsCategory").hide();
                //     $("#updateGoodsCategory").show();
                //     $("#deleteGoodsCategory").show();
                //     $("#newGoodsCategory").show();
                // } else {
                //     $("#downLoadGoodsCategory").show();
                //     $("#updateGoodsCategory").hide();
                //     $("#deleteGoodsCategory").hide();
                //     $("#newGoodsCategory").hide();
                // }
            } else{
                window.top.window.showModalAlert(data.errormessage);
            }

        },
        error:function(XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });

  //确认信息画面显示
    var loading = window.top.window.getIndexBusyOverlay();
    $.ajax({
        type: "GET",
        url: "/goods/getGoodsCategory.action",
        contentType: "application/json;charset=utf-8",
        dataType: "json",
//        async: false,//同步
        beforeSend:function(){
            if(loading) {
            	loading.settext("正在处理中，请稍后...");
            }
        },
        success: function (data) {
        	loading.remove();
            if (data.result == "success") {
                //设置商品分类
                  var heads = ["分类名称","备注","创建时间","修改时间"];
                  var goodsCategory = data.goodsCategory;
                  if (goodsCategory!==null){
                      $('#treeAction').show();
                      $.TreeTable("treeMenu", heads, goodsCategory);
                      treeTableShow= $("#treeMenu");
                      treeTableShow.treetable({ expandable: true });
                      // Highlight selected row
                      treeTableShow.find("tbody").on("mousedown", "tr", function() {
                          key = $(this).attr("key");
                          parentKey = $(this).attr("parentkey");
                          name = $(this).find("span:nth-child(2)").html();
                          remark = $(this).find("td:nth-child(2)").html();
                         $(".selected").removeClass("selected");
                          $(this).toggleClass("selected");
                      });
                      treeTableShow.treetable('expandAll');
                  } else {
                      $('#treeAction').hide();
                  }
                  
              } else {
                  window.top.window.showModalAlert(data.msg);
              }
        },
        error: function (XMLHttpRequest, textStatus) {
        	loading.remove();
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });
    
    
    
    $("#expandAll").click(function(){
        treeTableShow.treetable('expandAll'); return false;
    });
    
    $("#collapseAll").click(function(){
        treeTableShow.treetable('collapseAll'); return false;
    });
    
    $("#treeMenu .children, #treeMenu .parent").draggable({
      helper: "clone",
      opacity: .75,
      refreshPositions: true, // Performance?
      revert: "invalid",
      revertDuration: 300,
      scroll: true
  });

  $("#treeMenu .parent").each(function () {
      $(this).parents("tr").droppable({
          accept: ".children, .parent",
          drop: function (e, ui) {
              var droppedEl = ui.draggable.parents("tr");
              $("#treeMenu").treetable("move", droppedEl.data("ttId"), $(this).data("ttId"));
              var key = droppedEl.attr("key");
              var parentkey = $(this).attr("key");
              //ajax 数据库更新
              $.ajax({
                  type:"POST",
                  url:"/goodsCategory/changeGoodsCategory.action?newParentkey="+parentkey+"&key="+key,
                  contentType: "application/json;charset=utf-8",
                  dataType: "json",
                  async: false, // 同步
                  success:function(data) {
                      if (data.success == "y") {
//                         reloadGoodsCategory();
                      } else{
                          window.top.window.showModalAlert(data.errormessage);
                      }
                      
                  },
                  error:function(XMLHttpRequest, textStatus) {
                      if (XMLHttpRequest.status == 500) {
                          var result = eval("(" + XMLHttpRequest.responseText + ")");
                          alert(result.errorObject.errorText);
                      }
                  }
                  });
          },
          hoverClass: "accept",
          over: function (e, ui) {
              var droppedEl = ui.draggable.parents("tr");
              if (this != droppedEl[0] && !$(this).is(".expanded")) {
                  $("#treeMenu").treetable("expandNode", $(this).data("ttId"));
              }
          }
      });   
  });
  
//创建对话框关闭事件发生
  $('#modalCreate').on('hide.bs.modal', function () {
      // 父窗体归还本页的编辑对话框
      window.top.window.returnCustomModalDialog();
  })
  
  // 创建保存按钮点击事件绑定
    $("#btnGoodsCategorySave").click(function(){
        //取得分类名称
        var catgName  = window.top.window.$("#catgName").val();
        if (catgName==null || catgName==""){
            window.top.window.showModalAlert("请输入分类名称");
            return ;
        }
        
      //商品信息
        var goodsCategory = new Object();
        if (window.top.window.$("#key").val()==null || window.top.window.$("#key").val() == ""){
            goodsCategory.action = "insert";
            goodsCategory.key = "";
            goodsCategory.parentKey = key ;
        } else {
            goodsCategory.action = "update";
            goodsCategory.key = window.top.window.$("#key").val();
            goodsCategory.parentKey = "" ;
        }
        goodsCategory.catgName = catgName;
        goodsCategory.remark = window.top.window.$("#remark").val()
        window.top.window.returnCustomModalDialog();
        var loading = window.top.window.getIndexBusyOverlay();
      //后台交互
        $.ajax({
            type:"POST",
            url:"/goodsCategory/updateGoodsCategory.action",
            data:JSON.stringify(goodsCategory),
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            beforeSend:function(){
                if(loading) {
                	loading.settext("正在处理中，请稍后...");
                }
            },
//            async: false, // 同步
            success:function(data) {
            	loading.remove();
                if (data.success == "y") {
                    $('#modalCreate').modal('hide');
                   reloadGoodsCategory();
                } else{
                    window.top.window.showModalAlert(data.errormessage);
                    var editDialog = window.top.window.borrowCustomModalDialog($("#modalCreate"));
                    editDialog.modal({show:true, backdrop:'static'});
                }
                
            },
            error:function(XMLHttpRequest, textStatus) {
            	loading.remove();
                if (XMLHttpRequest.status == 500) {
                    var result = eval("(" + XMLHttpRequest.responseText + ")");
                    alert(result.errorObject.errorText);
                }
            }
            });
    });
  
////设置规则详情对话框关闭事件发生
//  $('#modalEnable').on('hide.bs.modal', function () {
//      // 父窗体归还本页的编辑对话框
//      window.top.window.returnCustomModalDialog();
//  })
  
});

function reloadGoodsCategory(){
    self.location.reload();
}

function downLoadGoodsCategory(){
    $.ajax({
        type:"POST",
        url:"/goodsCategory/downLoadGoodsCategory.action?key="+key,
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        async: false, // 同步
        success:function(data) {
            if (data.success == "y") {
                reloadGoodsCategory();
            } else{
                window.top.window.showModalAlert(data.errormessage);
            }

        },
        error:function(XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });
}
/**
 * 打开创建分单规则的对话框
 * @returns
 */
function newGoodsCategory() {
    $("#goodsCategoryForm")[0].reset();
    $("#key").val("");
    $("#editCatTitle").html("新增子分类");
    var editDialog = window.top.window.borrowCustomModalDialog($("#modalCreate"));
    editDialog.modal({show:true, backdrop:'static'});
}

function updateGoodsCategory() {
    if (key==null || key==""){
        window.top.window.showModalAlert("请选择要修改的分类");
        return ;
    }
    $("#goodsCategoryForm")[0].reset();
    $("#catgName").val(name);
    $("#remark").val(remark);
    $("#key").val(key);
    $("#editCatTitle").html("修改子分类");
    var editDialog = window.top.window.borrowCustomModalDialog($("#modalCreate"));
    editDialog.modal({show:true, backdrop:'static'});
}

function deleteGoodsCategory() {
    if (key==null || key==""){
        window.top.window.showModalAlert("请选择要删除的分类");
        return ;
    }
    
    window.top.window.showModalConfirm("是否立即删除商品分类？", operationDel);
}

function operationDel(){
    if (key==null || key==""){
        window.top.window.showModalAlert("请选择要删除的分类");
        return ;
    }
    var loading = window.top.window.getIndexBusyOverlay();
    $.ajax({
        type:"POST",
        url:"/goodsCategory/delGoodsCategory.action?key="+key,
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        beforeSend:function(){
            if(loading) {
            	loading.settext("正在处理中，请稍后...");
            }
        },
//        async: false, // 同步
        success:function(data) {
        	loading.remove();
            if (data.success == "y") {
               reloadGoodsCategory();
            } else{
                window.top.window.showModalAlert(data.errormessage);
            }
            
        },
        error:function(XMLHttpRequest, textStatus) {
        	loading.remove();
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
        });
}